<template>
  <div class="flex flex-wrap gap-4">
    <el-card style="font-size: 15px;font-weight: bold;margin-bottom: 10px" shadow="always"><span style="color: #535bf2">|</span> 订单列表页
    </el-card>
  </div>
  <div class="orderList" style="padding-top: 30px">
    <el-button style="margin-left: 15px;" type="primary" @click="addView">添加商品</el-button>

<!--    <el-button type="danger" @click="batchDel">批量删除</el-button>-->
    <el-form style="margin-top: 15px; margin-left: 15px " :inline="true" :model="orderSearchQuery">
      <el-form-item label="">
<!--        <el-select style="width: 150px"-->
<!--                   v-model="orderSearchQuery.id"-->
<!--                   placeholder="请选择商品"-->
<!--                   @click="loadUser"-->
<!--                   clearable>-->
<!--          <el-option-->
<!--              v-for="item in orderOptions"-->
<!--              :key="item.id"-->
<!--              :label="item.orderName"-->
<!--              :value="item.id"/>-->
<!--        </el-select>-->
      </el-form-item>
<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="onSearch">搜 索</el-button>-->
<!--        <el-button type="primary" plain @click="onReset">重 置</el-button>-->
<!--      </el-form-item>-->
    </el-form>
    <el-table
        :data="orderList"
        style="width: auto"
    >
      <el-table-column type="selection" width="50" show-overflow-tooltip/>
      <el-table-column type="index" label="序号" width="150" show-overflow-tooltip/>

      <!--      prop属性的值要和后端传过来的保持一致
      -->
      <el-table-column prop="id" label="订单ID" width="200" show-overflow-tooltip/>
      <el-table-column prop="createTime" label="订单创建时间" width="200" show-overflow-tooltip></el-table-column>

      <el-table-column prop="receivingAddress" label="收货地址" width="200" show-overflow-tooltip/>
      <el-table-column prop="userId" label="用户ID" width="200" show-overflow-tooltip/>
      <el-table-column style="" label="操作" width="230">

        <!--        scope.row.userId 表示当前这条数据的userId，详情和删除都要有userId（根据id查询或删除），user表中主键id是userId 所以这样-->
        <!--        其余表中看具体情况，一般是表中的主键都叫id 那就 scope.row.id -->
        <template #default="scope">
          <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
                    <el-button type="success" @click="editView(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="delUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="justify-content: center;margin-top: 10px"
                   background
                   layout="prev, pager,next"
                   :page-size=pageSize
                   :total=total
                   @current-change="toPage"
                   @prev-click="toPage"
                   @next-click="toPage"
    />
    <el-dialog v-model="dialogVisible" width="1000px" :title="orderQuery.id !=null ? '订单详情' : '新增订单'"
               draggable="true" center>

      <el-form-item label="收货地址：" prop="receivingAddress">
        <el-input type="text" v-if="orderQuery.id==null" v-model="orderQuery.receivingAddress"/>
        <span class="detail" v-else>{{ orderQuery.receivingAddress }}</span>
      </el-form-item>
<!--      <el-form-item label="用户ID：" prop="userId">-->
<!--        <el-input type="text" v-if="orderQuery.id==null" v-model="orderQuery.userId"/>-->

<!--        <span class="detail" v-else>{{ orderQuery.userId }}</span>-->
<!--      </el-form-item>-->

      <el-form-item  label="用户名：">
<!--        如果是添加，下拉菜单-->
        <el-select style="width: 150px"
                   v-if="orderQuery.userId==null"
                   v-model="orderQuery.userId"
                   placeholder="请选择用户"
                   @click="loadUser"
                   clearable>
          <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"/>
        </el-select>

<!--        否则就是详情，展示数据-->
        <span class="detail" v-else>{{ orderQuery.userId }}</span>
      </el-form-item>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="orderQuery.id==null" type="primary" @click="addOrderSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>



    <el-dialog v-model="editDialogVisible" width="1000px" draggable="true" center>
      <!--      是一个form表单，数据绑定到 userQuery-->
      <el-form ref="addRefForm" :model="editOrderQuery" label-width="auto"  style="max-width: 800px">

        <!--        userQuery.userId!=null 表示有数据，就是详情，才会展示下面的数据，否则不展示-->

<!--        <el-form-item label="ID：" prop="id">-->
<!--          <span class="detail">{{ editOrderQuery.id }}</span>-->
<!--        </el-form-item>-->
        <el-form-item label="收货地址：" prop="receivingAddress">
          <el-input v-model="editOrderQuery.receivingAddress"/>
        </el-form-item>
<!--        <el-form-item label="用户ID：" prop="userId">-->
<!--          <el-input v-model="editOrderQuery.userId"/>-->
<!--        </el-form-item>-->

        <el-form-item  label="用户名：">
          <el-select style="width: 150px"
                     v-model="editOrderQuery.userId"
                     placeholder="请选择用户"
                     @click="loadUser"
                     clearable>
            <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"/>
          </el-select>
        </el-form-item>


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editOrderSubmit">
            确定
          </el-button>

        </div>
      </template>

    </el-dialog>


  </div>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";
import qs from "qs";

export default {
  name: "OrderView",
  inject: ['reload'],
  data(){
    return{
      orderList:[],
      orderSearchQuery:{},
      dialogVisible: false,
      editOrderQuery: {},
      orderQuery: {},
      total: 0,
      editDialogVisible: false,
      pageSize: 0,
      idArray: [],
      userOptions: [{}],
      typeOptions: [{}],
      id:[
        {required:true,message:"请输入添加商品ID",trigger:'blur'},
      ],

    }
  },

  mounted() {
    this.loadOrderList(1);
  },
  methods:{
    toPage(current) {
      this.loadOrderList(current)
    },
    // 还没用到，先不用管(批量删除)
    handleSelectionChange(userItemArray) {
      this.userIdArray = [];
      userItemArray.forEach((user) => {
        this.userIdArray.push(user.userId);
      })

    },

    loadOrderList(current) {
      // 第一个参数为请求路径 第二个参数为请求所携带的参数，分页查询数据，携带current表示当前页数，后端通过req.getParameter("current")获取到
      doGet("/admin/order", {
        // 注意
        current: current,
        // userId:this.orderSearchQuery.userId,
        // createTime:this.orderSearchQuery.createTime,
      }).then((resp) => {
        // 打印后端响应的数据，F12调试控制台，查看返回的数据格式
        console.log(resp)

        if (resp.data.code === 200) {
          this.orderList = resp.data.data.list
          this.pageSize = resp.data.data.pageSize
          this.total = resp.data.data.total
        }
      })
    },
    view(id) {
      doGet("/admin/order/" +id).then((resp) =>{
        // 不管怎样，打印查看响应的resp 看看是否成功
        console.log(resp)
        // 200 表示成功，成功就可以进行数据绑定了，让后呈现数据了
        if (resp.data.code === 200) {
          // 根据最前面变量定义，userQuery表示  添加用户 或 查看用户详情 数据信息进行绑定
          this.orderQuery = resp.data.data
          // 表示打开弹窗 此时后端的数据已经绑定到userQuery中了
          this.dialogVisible = true
        }
      })
    },
    delUser(id) {
      // messageConfirm函数和messageTip函数都是封装的函数可以点开看一下，
      // messageConfirm函数会弹出一个弹窗 是否删除该用户如果点击了确认，就会执行后面then中的内容
      // messageTip函数表示信息弹窗
      messageConfirm("是否删除该用户？").then(() => {
        doDelete("/admin/order/"+id).then((resp) =>  {
          if (resp.data.code === 200) {
            messageTip("删除成功!", "success")
            this.reload()
          }
        })
      })
    },
    batchDel() {

      let ids = this.userIdArray.join(",");
      doGet("/admin/order?method=deleteByIds", {
        ids: ids
      })

    },
    // 该方法表示加载用户信息，查询所有用户信息 。具体效果在用户列表根据name查询 下拉框
    loadUser() {
      doGet("/admin/user", {current: "1"}).then((resp) => {
        console.log(resp.data.data.list)
        if (resp.data.code === 200) {
          // 将后端的数据信息赋值给 userOptions,数据绑定，后续可以在下拉框中取出
          this.userOptions = resp.data.data.list
        }
      })
    },
    onReset() {
      this.orderSearchQuery = {}
    },
    addView() {
      // 添加用户确保userQuery中没数据 然后在弹开
      // userQuery在根据id查询用户时进行了数据绑定，添加用户时，userQuery中的数据没用了，清空，
      this.orderQuery = {}
      this.dialogVisible = true
    },
    addOrderSubmit() {
      // 使用qs将数据格式化了 { encode: false }表示不会出现中文乱码
      // this.userQuery中的数据就是弹出添加用户弹窗中form表单所绑定的数据(具体看所对应的表单)，
      // 使用post请求时，必须使用qs将数据格式化！！！！！！
      // let data = qs.stringify(this.orderQuery, {encode: false})
      // console.log(data)
      doPost("/admin/order/save", this.orderQuery).then((resp) => {
        if (resp.data.code === 200) {
          this.dialogVisible = false
          messageTip("添加成功", "success")
          // 添加数据成功，需要进行页面刷新 调用该方法
          this.reload()
        } else {
          messageTip("添加失败", "error")
        }
      })
    },
    editView(id) {
      doGet("/admin/order/"+id).then((resp) =>{
        console.log(resp)
        if (resp.data.code === 200) {
          this.editOrderQuery = resp.data.data
          this.editDialogVisible = true
        }
      })
    },

    editOrderSubmit() {
      // let data = qs.stringify(this.editOrderQuery, {encode: false})
      // console.log(data)
      doPut("/admin/order", this.editOrderQuery).then((resp) => {
        console.log(resp)
        if (resp.data.code === 200) {
          this.editDialogVisible=false
          messageTip("修改成功！","success")
          this.reload()
        }
      })
    },
  }

}
</script>

<style scoped>
.orderList {

  width: auto;
  height: auto;
  background-color: #ffffff;
}

.detail {
  background-color: #f5f7fa;
  width: 100%;
  padding-left: 15px;
}

</style>